package com.itheima.service.impl;

import ch.qos.logback.core.model.conditional.ElseModel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.apache.catalina.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {
    @Autowired
    private EmpExprService empExprService;
    @Autowired
    private DeptMapper deptMapper;

    @Override
    public Result getPageResult(EmpQueryParam param) {
        String name=param.getName();
        Integer gender = param.getGender();
        LocalDate begin = param.getBegin();
        LocalDate end = param.getEnd();
        Page<Emp> page = new Page<>(param.getPage(),param.getPageSize());
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name),Emp::getName,name)
                .eq(ObjectUtils.isNotNull(gender),Emp::getGender,gender)
                .between(ObjectUtils.isNotNull(begin) && ObjectUtils.isNotNull(end),Emp::getEntryDate,begin,end);
        this.page(page,queryWrapper);
        //部门名称没有显示处理
        List<Emp> emps = page.getRecords();
        //遍历，stream流
        Set<Integer> deptIds = emps.stream().map(Emp::getDeptId).collect(Collectors.toSet());
        if (!deptIds.isEmpty()) {
            List<Dept> depts = deptMapper.selectList(new LambdaQueryWrapper<Dept>().in(Dept::getId, deptIds));
            //将depts收集成一个Map
            Map<Integer, String> deptMap = depts.stream().collect(Collectors.toMap(Dept::getId, Dept::getName));
            emps.forEach(emp -> emp.setDeptName(deptMap.get(emp.getDeptId())));
        }

        PageResult<Emp> empPageResult = new PageResult<>(page.getTotal(),emps);
        return Result.success(empPageResult);
    }

    @Override
    @Transactional
    public boolean saveEmpAndExpr(Emp emp) {
        this.save(emp);
        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(v->v.setEmpId(emp.getId()));
        empExprService.saveBatch(exprList);
        return true;
    }
}
